package com.kczd.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.kczd.adapter.OrderPagerAdapter;
import com.kczd.client.R;
import com.kczd.entity.Location;
import com.kczd.fragment.OrderFinishedFragment;
import com.kczd.fragment.OrderOverFragment;
import com.kczd.fragment.OrderNotFragment;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.util.SysApplication;
import com.kczd.view.NoScrollViewPager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * zhangy
 * Created by Administrator on 2017/3/6.
 */

public class GochenGoActivity extends AppCompatActivity {

    private View view;
    private RadioGroup  order_rg;
    private RadioButton order_not_pay;//未支付订单
    private RadioButton order_finsh_pay;//已完成订单
    private RadioButton order_over_pay;//已取消订单

    private NoScrollViewPager vp_order;
    private OrderPagerAdapter vp_order_adapter;

    SweetAlertDialog pDialog = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_go_cheng);

        if(Common.user != null)
        {
            new Thread(){
                @Override
                public void run()
                {
                    getOrder(Common.otype_1);
                }
            }.start();
        }
        setview();
        // 多activity管理
        SysApplication.getInstance().addActivity(this);
    }
    private void setview() {
        order_rg=(RadioGroup) findViewById(R.id.order_rg);
        order_not_pay =(RadioButton)findViewById(R.id.order_not_pay);
        order_finsh_pay =(RadioButton)findViewById(R.id.order_finsh_pay);
        order_over_pay =(RadioButton)findViewById(R.id.order_over_pay);
        vp_order=(NoScrollViewPager)findViewById(R.id.vp_order);
        vp_order_adapter = new OrderPagerAdapter(getSupportFragmentManager());
        vp_order.setAdapter(vp_order_adapter);

        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);

        vp_order.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // TODO Auto-generated method stub
                switch (position) {
                    case 0:
                        order_not_pay.setChecked(true);
                        break;
                    case 1:
                        order_finsh_pay.setChecked(true);
                        break;
                    case 2:
                        order_over_pay.setChecked(true);
                        break;
                }
            }
            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });
        order_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                switch (checkedId) {
                    case R.id.order_not_pay:
                        pDialog.show();
                        new Thread(){
                            @Override
                            public void run()
                            {
                                getOrder(Common.otype_1);
                            }
                        }.start();
                        break;
                    case R.id.order_finsh_pay:
                        pDialog.show();
                        new Thread(){
                            @Override
                            public void run()
                            {
                                getOrder(Common.otype_5);
                            }
                        }.start();
                        break;
                    case R.id.order_over_pay:
                        pDialog.show();
                        new Thread(){
                            @Override
                            public void run()
                            {
                                getOrder(Common.otype_0);
                            }
                        }.start();
                        break;
                    default:
                        break;
                }
            }
        });
    }
    String url = Common.net_addr + "itf/tx_get_orders_info.php";

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e("zhangy","val的值是："+val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            String otype = data.getString("otype");
            JSONObject jsonResult;
            try {
                pDialog.dismiss();
                jsonResult = new JSONObject(val);

                if(otype.equals(Common.otype_1)){
                    OrderNotFragment.orderNotlsit.clear();
                }else if(otype.equals(Common.otype_0)){
                    OrderOverFragment.orderOverlsit.clear();
                }else if(otype.equals(Common.otype_5)){
                    OrderFinishedFragment.orderFinishedlsit.clear();
                }
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    JSONArray jsarr =  jsonResult.getJSONArray("list_Arr");
                    if(jsonResult.getInt("ilist")==0){
                        Toast.makeText(GochenGoActivity.this, "没有相关数据", Toast.LENGTH_SHORT).show();
                    }else {
                        for (int i = 0; i < jsonResult.getInt("ilist"); i++) {
                            JSONObject jso = jsarr.getJSONObject(i);
                            Location item = new Location();
                            item.setDatetime(jso.getString("createTime"));
                            item.setOrigin(jso.getString("oripos"));
                            item.setTerminal(jso.getString("endpos"));
                            item.setOkey(jso.getString("okey"));
                            item.setU_name(jso.getString("driver_name"));
                            item.setU_tel(jso.getString("driver_tel"));
                            item.setU_img(jso.getString("driver_img"));
                            item.setLink_pos(jso.getString("link_pos"));
                            item.setTol_price(jso.getString("tol_price"));
                            item.setLi(jso.getString("li"));
                            item.setPrice_qibujia(jso.getString("price_qibujia"));
                            item.setPrice_shichangfei(jso.getString("price_shichangfei"));
                            item.setPrice_yuantufei(jso.getString("price_yuantufei"));
                            item.setOrigin_lat(jso.getString("origin_lat"));
                            item.setOrigin_lng(jso.getString("origin_lng"));
                            item.setTerminal_lat(jso.getString("terminal_lat"));
                            item.setTerminal_lng(jso.getString("terminal_lng"));

                            if (otype.equals(Common.otype_1)) {
                                item.setType(R.mipmap.quxiao);
                                OrderNotFragment. orderNotlsit.add(item);
                            } else if (otype.equals(Common.otype_0)) {
                                item.setType(R.mipmap.phone_weizhifu);
                                OrderOverFragment.orderOverlsit.add(item);
                            } else if (otype.equals(Common.otype_5)) {
                                item.setType(R.mipmap.nothing);
                                OrderFinishedFragment.orderFinishedlsit.add(item);
                            }
                        }

                    }
                }else{
                    Toast.makeText(GochenGoActivity.this, jsonResult.getString("err"),
                            Toast.LENGTH_SHORT).show();
                }
                if(otype.equals(Common.otype_1)){
                    vp_order.setCurrentItem(0,false);
                }else if(otype.equals(Common.otype_5)){
                    vp_order.setCurrentItem(1,false);
                }else if(otype.equals(Common.otype_0)){
                    vp_order.setCurrentItem(2,false);
                }

                vp_order_adapter.notifyDataSetChanged();

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    public void getOrder(String otype) {

        Log.e("zhangy","server get data");
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("otype", otype)
                .add("utype", Common.utype)
                .add("ukey", Common.user.getUkey())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            data.putString("otype", otype);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
